<?
include_once "./src/facebook.php";
include_once "./Post.php";
include_once "./MultiRequest.php";


class FacebookQuery {
 

  private $facebook;
  private $request; 
  private $token;
  /* @author Leonardo Rania
   public function __construct(){}
  */
 
  
  
  /* @author Leonardo Rania
  Input : Facebook obj
  */
  public function __construct(Facebook $facebook)
  {
		$this -> facebook = clone $facebook;
		$this -> request = new MultiRequest();
		$this -> token = $this -> facebook -> getAccessToken();
  }
  
  /* @author Leonardo Rania
  This function sets the Facebook Obj values, if you already haven't done in the costruct.
  Input : Facebook obj
  */
  public function setFacebookObj(Facebook $facebook)
  {
		$this -> facebook = clone $facebook;
  }
  
  /* @author Leonardo Rania
  This function returns all the information about me(user)
  Output: Array like this : name -> Leonardo surname-> Rania userName -> Leonardo Rania etc....
  */
  public function myInformations()
  {
	  return $this -> facebook -> api('/me');
  }
  
  
  /* @author Leonardo Rania
  This function returns all the posts that the user Mr. X published in his wall
  Input:  Id Mr.X
  Output: Array of posts' Mr. X 
  */
  public function allPosts($IDuser)
  {
	  
	  //Variable to understand when there aren't more posts
		  $finishedPosts = 0;
	
	  //Create allPosts
	  $allPosts = array_fill(0, count($post['data']), new Post());
   
	  //Take all posts and put this ones in a Array
	  $data = array ('https://graph.facebook.com/'.$IDuser.'/posts?limit=1000&access_token='.$this-> token , 'https://graph.facebook.com/'.$IDuser.'/statuses?limit=1000&access_token='.$this->token);
	  $response = $this -> request -> multiRequest($data);
	  echo "prima richiesta simultanea posts e statuses <br />";
	  $posts = json_decode($response[0],true);
  	  $statuses = json_decode($response[1],true);
 
	  
	  /*Take all the informations, like people that was tagged in a post, people that have put likes 
	  	or have put a comment*/
	  $pos = 0;
	  while (!$finishedPosts)
	  {
		//The next Page
  		$nextPag = $posts['paging']['next'];
  		$nextPagStatuses = $statuses['paging']['next'];	
     
		for( $i = 0 ; $i < count($posts['data']); $i++)
		{
			//Take $i-post
			$post = $posts['data'][$i];
			
			/*If in the post there is the field type = status does mean that Mr.X has comments or has put likes 		
			or etc.. but on an other wall and so we can delete this kind of post*/
			
			//if($post['type'] != 'status' || !$post['story'])
			//{
				$allPosts[$pos] -> created_time = $post['created_time'];
				$allPosts[$pos] -> id_post = $post['id'];
				
				//Take the message and put this last in allPosts-> message
				$allPosts[$pos] -> message = $post['message'];
				
				//Check if there are people tagged and if there are store them in allPosts -> tagsPeople
				if($post['to']['data'])
				{
					$allPosts[$pos] -> tagsPeople = $this -> getPeopleTagged($post['to']);
				}
				
				/*Check if there are comments and if there are take comments and its informations and 
				put this ones in allPosts -> numComments, allPosts -> commentsPeople and allPosts -> comments
				*/
				if($post['comments']['count'] > 0)
				{
					$commentsInfo = $this -> getComments($post['comments'], $statuses, $post['id']);
					$allPosts[$pos] -> comments = $commentsInfo[0];
					$allPosts[$pos] -> numComments = $commentsInfo[1];
                }
				else
					$allPosts[$pos] -> numComments = 0;
					
				//As above but for the likes	
				if($post['likes']['count'] > 0)
				{
					$likesInfo = $this -> getLikes($post['likes'], $statuses, $post['id']);
					$allPosts[$pos] -> likesPeople = $likesInfo[0]; 
					$allPosts[$pos] -> numLikes = $likesInfo[1];
				}
				else
					$allPosts[$pos] -> numLikes = 0;
					
			$pos++;		
			//}//close if 
			
		}

		if($nextPag)
		{
			//Work on the nextPage Url to extract "Until"
			$dataNextPagePosts = split('&',$nextPag);
			$dataNextPageStatuses = split('&',$nextPagStatuses);
	  $data = array ('https://graph.facebook.com/'.$IDuser.'/posts?limit=1000&access_token='.$this-> token.'&'.$dataNextPage[3] , 'https://graph.facebook.com/'.$IDuser.'/statuses?limit=1000&access_token='.$this->token.'&'.$dataNextPageStatuses[3]);

echo "next richiesta simultanea <br />";
	        $response = $this -> request -> multiRequest($data);
		    $posts = json_decode($response[0],true);
  	  		$statuses = json_decode($response[1],true);
	  		$nextPag = null;
			$nextPagStatuses = null;
			$finishedPosts = 0; //CHANGE IT
		}
		else
		{
			$finishedPosts = 1;
		}

	  }
		
		
		return $allPosts;
	  	
  }
  
  
  /*@author Leonardo Rania
  This function get all People tagged in a post
  */
  private function getPeopleTagged($tagsArray)
  {
	  	for($i = 0 ; $i < count($tagsArray['data']); $i++)
		{
			$tagsPeople[$i] = array('id' => $tagsArray['data'][$i]['id'], 
	        					    'name' => $tagsArray['data'][$i]['name']);
		}
		
	return $tagsPeople;
  }
  
   /*@author Leonardo Rania
  This function get all comments and the informations about its 
  */
  private function getComments($commentsArray, $statusesArray ,$idPost)
  {
	$numComments = $commentsArray['count'];
		   
    //All comments
  	//If graph posts not visualize all the commments... 
	if($numComments != count($commentsArray['data']))
	{
		$posStatuses = $this -> isStatuses($idPost, $statusesArray);
		
		if($posStatuses)
		{
			$commentsData = $statusesArray['data'][$posStatuses]['comments']['data'];
		}
		else
		{
			$commentsData = $this -> facebook -> api($idPost.'/comments?limit='.$numComments);
			echo "richiesta commento <br />";
			$commentsData = $commentsData['data'];
		}
		

	}
	else
		$commentsData = $commentsArray['data'];
			 
		
	for($i = 0 ; $i < $numComments ; $i++)
	{
		//Store comment
		$comments[$i] = array('id' => $commentsData[$i]['from']['id'], 
									'message' => $commentsData[$i]['message']);
	}
	
	$result = array($comments, $numComments);
	
	return $result;

  }
  
  /*@author Leonardo Rania
  This function get all likes and the informations about its 
  */
  private function getLikes($likesArray,$statusesArray, $idPost)
  {
	//Store numLikes
	$numLikes = $likesArray['count'];
			
    //If graph posts not visualize all the likes 
	if($numLikes != count($likesArray['data']))
	{
		$posStatuses = $this -> isStatuses($idPost, $statusesArray);
		
		if($posStatuses)
		{
			$likesData = $statusesArray['data'][$posStatuses]['likes']['data'];
		}
		else
		{
			$likesData = $this -> facebook -> api($idPost.'/likes?limit='.$numLikes);
			echo "richiesta like <br />";
			$likesData = $likesData['data'];
		}
	}
	else
		$likesData = $likesArray['data'];
				
	for($i = 0 ; $i < $numLikes ; $i++)
	{
		$likesPeople[$i]['id'] = $likesData[$i]['id'];
	}
	
	$result = array($likesPeople, $numLikes);
	
	return $result;
  }
  
   private function isStatuses($idPost, $statusesArray)
   {
	   $finalID = null;
	   
	   $id = split('_',$idPost);
	   
	   for($i = 0 ; $i < count($statusesArray['data']); $i++)
	   {
		   if($statusesArray['data'][$i]['id'] == $id[1])
		   {
			   $finalID = $i;
			   break;
		   }
	   }
	   return $finalID;
   }
  
  
  
}

?>